package com.example.gulimall.common.config;

import com.example.gulimall.common.perporties.SecurityProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;

/**
 * <p>@description: token缓存  </p>
 * <p>@author: JGD </p>
 * <p>@create: 2020/3/17 16:57 </p>
 * <p>@version : 2.0.0
 **/
@Configuration
public class TokenStoreConfig {


    /**
     * redis
     */
    @Configuration
    @ConditionalOnProperty(prefix = "base.security.oauth2", name = "token-store-type", havingValue = "redis")
    public static class RedisConfig {
        @Resource
        private RedisConnectionFactory redisConnectionFactory;

        @Bean
        public TokenStore redisTokenStore() {
            return new RedisTokenStore(redisConnectionFactory);
        }
    }

    /**
     * jwt
     */
    @Configuration
    @ConditionalOnProperty(prefix = "base.security.oauth2", name = "token-store-type", havingValue = "jwt", matchIfMissing = true)
    public static class JwtConfig{
        @Resource
        private SecurityProperties securityProperties;
        /**
         * 使用jwtTokenStore存储token
         *
         * @return
         */
        @Bean
        public TokenStore jwtTokenStore() {
            JwtTokenStore jwtTokenStore = new JwtTokenStore(jwtAccessTokenConverter());
            return jwtTokenStore;
        }

        /**
         * 用于生成jwt
         *
         * @return
         */
        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
            //秘签
            jwtAccessTokenConverter.setSigningKey(securityProperties.getJwtSigningKey());
            return jwtAccessTokenConverter;
        }
    }
}
